package com.lagace.spark.twitter;

import java.awt.BorderLayout;
import java.awt.Cursor;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.html.HTMLDocument;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.HTML.Tag;

import winterwell.jtwitter.Twitter;
import winterwell.jtwitter.Twitter.Status;

public class TwitterTimelinePane extends JScrollPane implements Runnable {
	private static final long serialVersionUID = 1L;
	private Twitter t;
	private HTMLDocument doc;
	private HTMLEditorKit kit;
	private boolean shutDown = false;
	private int refreshTime;
	private int lastTweet; 
	
	public TwitterTimelinePane(Twitter t, int refreshTime) {
		this.t = t;
		this.refreshTime = refreshTime;
        buildUI();
	}
	
	public void buildUI() {
		String timeline = getFriendsTimeline();		
		doc = new HTMLDocument();
		kit = new HTMLEditorKit();
		kit.setLinkCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
		
		try {
			kit.insertHTML(doc, 0, timeline.toString(), 0, 0, Tag.HTML);
		} catch (BadLocationException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		JTextPane textPane = new JTextPane();
		textPane.setContentType("text/html");
		textPane.setEditorKit(kit);
		textPane.setEditable(false);
		textPane.setStyledDocument(doc);
		textPane.addHyperlinkListener(new HyperlinkListener(){
			public void hyperlinkUpdate(HyperlinkEvent e) {
				if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED)
					BrowserLaunch.openURL(e.getURL().toString());
			}
		});
		
		this.getViewport().add(textPane, BorderLayout.CENTER);
	}

	public String getFriendsTimeline() {
		List timeLines = t.getFriendsTimeline(); 
		Iterator i = timeLines.iterator();
		StringBuffer sb = new StringBuffer("<html><body><table>");
		int row = 0;
		Status status = null;
		while(i.hasNext()){
			status = (Status) i.next();
			showToastFor(status);
			sb.append("<tr>").append("<td valign=\"top\"><img width=\"32\" height=\"32\" src=\"").append(status.getUser().getProfileImageUrl().toString()).append("\" /></td>");
			sb.append("<td valign=\"top\"><a style=\"color:blue;font-weight:bold\" href=\"http://www.twitter.com/").append(status.getUser().getScreenName()).append("/\">").append(status.getUser().getName()).append("</a>: ");
			sb.append(TwitterUtil.insertAnchors(status.getText()));
			sb.append(" <i style=\"color:gray\">(" + TwitterUtil.toTimelineFormat(status.getCreatedAt().getTime(), System.currentTimeMillis()) + ")</i>").append("</td>").append("</tr>");
			row++;
		}
		if(isBlank(timeLines)) lastTweet = ((Status)timeLines.get(0)).getId();
		sb.append("</table></body></html>");
		System.out.println(sb.toString());
		return sb.toString();
	}

	private void showToastFor(Status status) {
		if(lastTweet != 0 && status.getId() > lastTweet){
			TwitterUtil.showToastFor(status);
		}
	}
	
	boolean isBlank(List timeLines) {
		return null != timeLines && !timeLines.isEmpty();
	}
	
	public void run() {
		while (!shutDown) {
	        try{
				Thread.sleep(refreshTime * 60 * 1000); //sleep for 2 minutes
		        doc.remove(0, doc.getLength());
		        kit.insertHTML(doc, 0, getFriendsTimeline(), 0, 0, Tag.HTML);
		        this.doLayout();
		        this.validate();
	        } catch (Exception e) {
				e.printStackTrace();
	        }
	    }
	}

	public void shutDown() {
		this.shutDown = true;
	}
}